package com.xxxx.server.config.security.component;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationProvider;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.security.auth.login.Configuration;
import java.util.Collection;

/**
 * 权限控制
 * 判断用户角色
 *
 * @author Ding Yi
 */

@Component
/*         AccessDecisionManager     访问决策管理器          */
public class CustomUrlDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        //   < collection >  里存放着   < CustomFilter >   过滤出来的角色
        for (ConfigAttribute configAttribute : collection) {
            /*当前URL所需要的角色*/
            String nodeRole = configAttribute.getAttribute();
            /*判断角色是否登录即可访问的角色，此角色在CustomFilter中设置*/
            if ("ROLE_LOGIN".equals(nodeRole)) {
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw new AccessDeniedException("尚未登录，请登录，^_^  ----  CustomUrlDecisionManager");
                }else {
                    return;
                }
            }
            /*判断用户角色是否为url需要的角色*/
            // authentication 里面存放着登录后的用户信息
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                // 访问该路径需要的角色与账号的角色相比较
                if (authority.getAuthority().equals(nodeRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员，^_^  -----  CustomUrlDecisionManager");

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
